package net.wesley.android.city;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import net.wesley.android.City;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class ShangHai extends City {

	@Override
	public boolean match(String chepai) {
		return chepai.startsWith("沪");
	}

	@Override
	public String[] paramDesc() {
		String[] s={"发动机号"};
		return s;
	}

	public void requestParamsFinish(String[] values) {
		final String chejia=values[0];
		final DefaultHttpClient httpClient = new DefaultHttpClient();  
		try {
			HttpGet get = new HttpGet("http://www.shjtaq.com/zwfg/dzjc_new.asp");
			httpClient.execute(get);
			
			HttpResponse rsp = httpClient.execute(new HttpGet("http://www.shjtaq.com/zwfg/validatecode.asp"));			
			Bitmap bmp= BitmapFactory.decodeStream(rsp.getEntity().getContent());
			if (bmp==null){
				callback.onComplete(-10006, "ret:获取验证码的时候遇到网络错误，请重试!");
				return;
			}
			LinearLayout table=new LinearLayout(ctx);
			table.setOrientation(LinearLayout.VERTICAL);
			ImageView v=new ImageView(ctx);
			v.setImageBitmap(bmp);
			v.setScaleType(ImageView.ScaleType.FIT_XY);
			LayoutParams p = new LinearLayout.LayoutParams(200,50);
			p.gravity=Gravity.CENTER;
			table.addView(v,p);
			final EditText t=new EditText(ctx);
			table.addView(t,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
			new AlertDialog.Builder(ctx).setTitle("请输入下图中的验证码").setView(table).setNegativeButton("确定", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					new Handler().postDelayed(new Runnable(){

						public void run() {
							HttpPost post=new HttpPost("http://www.shjtaq.com/zwfg/dzjc_new.asp");
							try {
								post.setEntity(new StringEntity(String.format("cardqz=%s&carnumber=%s&type1=02%%2F%%D0%%A1%%D0%%CD%%C6%%FB%%B3%%B5%%BA%%C5%%C5%%C6&fdjh=%s&verify=%s&act=search&submit=+%%CC%%E1+%%BD%%BB+",
										URLEncoder.encode("沪","GBK"),
										chepai.substring(1),chejia,t.getText().toString())));
								post.setHeader("Content-Type","application/x-www-form-urlencoded");
								post.setHeader("Referer", "http://www.shjtaq.com/zwfg/dzjc_new.asp");
								HttpResponse rsp = httpClient.execute(post);
								BufferedReader br;
								br = new BufferedReader(new InputStreamReader(rsp.getEntity()
										.getContent(),"GBK"));
								String line, result = "";
								while ((line = br.readLine()) != null) result += line+"\n";
								processResult(result);
							} catch (UnsupportedEncodingException e) {
								callback.onComplete(-10003, "");
							} catch (ClientProtocolException e) {
								callback.onComplete(-10004, "");
							} catch (IOException e) {
								callback.onComplete(-10005, "");
							}
						}						
					}, 1000);
				}
			}).create().show();
		} catch (ClientProtocolException e) {
			callback.onComplete(-10001, "");
		} catch (IOException e) {
			callback.onComplete(-10002, "");
		}
	}

	private void processResult(String result) {
		if (result.indexOf("<html>")<0){
			int index=result.indexOf("\talert(\"");
			if (index>0){
				callback.onComplete(-10031, "ret:"+result.substring(index+8).split("\"")[0]);
				return;
			}
			else{
				callback.onComplete(-10032, "");
				return;
			}
		}
		int index=result.indexOf("电子监控查询结果");
		String ret="";
		int total=0;
		if (index>0){
			String body1=result.substring(index).split("</table")[0];
			index=body1.indexOf("<td rowspan=\"7\"");
			if (index>0){
				String[] rows=body1.split("<td rowspan=\"7\"");
				for (int i=1;i<rows.length;i++){
					String[] values=rows[i].split("<td");
					String shijian=values[2].split("</div")[0].split(">")[2].trim();
					String didian=values[6].split("</div")[0].split(">")[2].trim();
					String reason=values[10].split("</div")[0].split(">")[2].trim();
					ret+=String.format("shijian:%s\ndidian:%s\ncode:%s\n\n",shijian,didian,reason);
					total+=1;
				}
			}
		}
		
		index=result.indexOf("违法停车查询结果");
		if (index>0){
			String body1=result.substring(index).split("</table")[0];
			index=body1.indexOf("<td rowspan=\"8\"");
			if (index>0){
				String[] rows=body1.split("<td rowspan=\"8\"");
				for (int i=1;i<rows.length;i++){
					String[] values=rows[i].split("<td");
					String shijian=values[2].split("</div")[0].split(">")[2].trim();
					String didian=values[8].split("</div")[0].split(">")[2].trim();
					String reason=values[12].split("</div")[0].split(">")[2].trim();
					ret+=String.format("shijian:%s\ndidian:%s\ncode:%s\n\n",shijian,didian,reason);
					total+=1;
				}
			}
		}
		if (total==0){
			ret="ret:没有获取到任何违章，请注意，如果您的输入的发动机号不正确，也将是这样的查询结果。";
		}
		callback.onComplete(total, ret);
	}

}
